<script setup>
import { ref, watchEffect } from 'vue'
import {
  Form,
  Field,
  CellGroup,
  Icon,
  Picker,
  Popup,
  showLoadingToast,
  Search,
} from 'vant'
import {
  goodsEnNameValidator,
  goodsCnNameValidator,
  goodsQuantityValidator,
  amountValidator,
} from '@/utils/validator.js'
import Utility from '@/utils/utility'
import commonModel from '@/http/modules/common.js'
import cgToast from '@/components/toast/index.js'
import { enumStore } from '@/store/enum'
import { storeToRefs } from 'pinia'
const emits = defineEmits(['checkSuccess'])
defineExpose({ checkForm, sketchForm })
const enum_store = enumStore()
const { enumDslInfo } = storeToRefs(enum_store)
const RefProductsForm = ref()
const categoryList = ref([])
const unitList = ref([])
let showCategoryPicker = ref(false)
let showUnitPicker = ref(false)
let activeProductIndex = ref(0)
const isSketch = ref(false)
const categorySearchKey = ref('')
const props = defineProps({
  contractDetail: {
    type: Object,
    default: () => {},
  },
  contractId: {
    // 是否是报关单
    type: [String, Number],
    default: '',
  },
  editContractId: {
    // 编辑id
    type: [String, Number],
    default: '',
  },
})
const productList = ref([
  {
    goodsCategoryDesc: '',
    goodsUnitName: '',
    goodsUrl: '', // 商品/店铺网址
    goodsCategory: '', // 商品类目
    goodsEnName: '', // 商品英文名称
    goodsCnName: '', // 商品中文名称
    goodsQty: '', // 商品数量
    goodsUnit: '', //	商品单位
    goodsUnitPrice: '', // 商品单价
  },
])
function handleAddProduct() {
  productList.value.push({
    goodsUnitName: '',
    goodsUrl: '', // 商品/店铺网址
    goodsCategory: '', // 商品类目
    goodsEnName: '', // 商品英文名称
    goodsCnName: '', // 商品中文名称
    goodsQty: '', // 商品数量
    goodsUnit: '', //	商品单位
    goodsUnitPrice: '', // 商品单价
  })
}
function checkForm() {
  isSketch.value = false
  RefProductsForm.value.submit()
}
function sketchForm() {
  isSketch.value = true
  onSubmit()
}
watchEffect(() => {
  categoryList.value = enumDslInfo.value.GoodsCategoryEnum
  if (enumDslInfo.value.GoodsUnit && enumDslInfo.value.GoodsUnit.length) {
    unitList.value = enumDslInfo.value.GoodsUnit.map((v) => ({
      ...v,
      text: v.label,
    }))
  }
})
function deleteProductItem(index) {
  productList.value.splice(index, 1)
}
function onCategoryConfirm({ selectedOptions }) {
  showCategoryPicker.value = false
  const { value, label } = selectedOptions[0]
  productList.value[activeProductIndex.value].goodsCategoryDesc = label
  productList.value[activeProductIndex.value].goodsCategory = value
}
function onUnitConfirm({ selectedOptions }) {
  showUnitPicker.value = false
  const { value, text } = selectedOptions[0]
  productList.value[activeProductIndex.value].goodsUnit = value
  productList.value[activeProductIndex.value].goodsUnitName = text
}
function handleToShowCatePicker(index) {
  activeProductIndex.value = index
  showCategoryPicker.value = true
}
function handleToShowUnitPicker(index) {
  activeProductIndex.value = index
  showUnitPicker.value = true
}
async function onSubmit() {
  let loading = null
  const params = {
    contractOrderNo: props.contractId,
    goodsCategory: productList.value[0].goodsCategory,
    goodsList: productList.value,
    goodsUrl: productList.value[0].goodsUrl,
    source: sessionStorage.source || '',
  }
  try {
    loading = showLoadingToast({
      duration: 0,
      message: '请求中...',
      forbidClick: true,
    })
    if ([undefined, 'Draft'].includes(props.contractDetail.contractStatus)) {
    commonModel
      .gatewayApi({
        bizContent: params,
        service: 'cb_trade_temp_store_goods',
        version: '1.0.0',
      })
      .then((result) => {
        if (result) {
          if (isSketch.value) {
            //暂存
            cgToast.open({
              title: '暂存成功',
              cancelText: '返回',
              confirmText: '下一步',
              confirmFun: () => {
                cgToast.close()
                checkForm()
              },
              cancelFun: () => {
                cgToast.close()
              },
            })
          } else {
            emits('checkSuccess', params)
          }
        }
      })
      .catch((error) => {
        if (isSketch.value) {
          // 暂存失败处理
          cgToast.open({
            title: '暂存失败',
            content: error.subMsg || error.msg,
            type: 'warning',
            showCancel: false,
            confirmFun: () => {
              cgToast.close()
            },
          })
        }
      })
    } else {
      emits('checkSuccess', params)
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading && loading.close()
  }
}
watchEffect(() => {
  if (props.editContractId) {
    if (props.contractDetail && JSON.stringify(props.contractDetail) !== '{}') {
      productList.value = [...props.contractDetail.goodsList]
      const { goodsUrl, goodsCategory } = props.contractDetail
      productList.value[0] = {
        ...productList.value[0],
        goodsUrl,
        goodsCategory,
        goodsCategoryDesc: Utility.getTargetByValue(
          enumDslInfo.value.GoodsCategoryEnum,
          goodsCategory
        ).name,
      }
    }
  }
})
async function handleCategorySearch(key) {
  key = key.trim()
  if (key) {
    categoryList.value = enumDslInfo.value.GoodsCategoryEnum.filter(
      (it) => it.label.indexOf(key) !== -1
    )
  } else {
    categoryList.value = enumDslInfo.value.GoodsCategoryEnum
  }
}
</script>

<template>
  <div class="contract__product">
    <Form label-width="7em" ref="RefProductsForm" @submit="onSubmit">
      <div
        v-for="(item, index) in productList"
        class="product__item"
        :key="index"
      >
        <div class="product__item-header">
          <span>{{ index === 0 ? '商品信息' : '' }}</span>
          <span
            v-if="index !== 0"
            class="delete__btn"
            @click="deleteProductItem(index)"
            >删除</span
          >
        </div>
        <CellGroup>
          <template v-if="index === 0">
            <Field
              v-model="item.goodsUrl"
              name="goodsUrl"
              label="商品/店铺地址"
              placeholder="请输入商品/店铺地址"
              :rules="[{ required: true, message: '请输入商品/店铺地址' }]"
            />
            <Field
              v-model="item.goodsCategoryDesc"
              name="goodsCategory"
              label="商品类目"
              placeholder="请选择"
              readonly
              is-link
              :rules="[{ required: true, message: '请选择商品类目' }]"
              @click="handleToShowCatePicker(index)"
            />
          </template>
          <Field
            v-model="item.goodsEnName"
            name="goodsEnName"
            label="商品英文名称"
            placeholder="请输入商品英文名称"
            :rules="[
              { required: true, message: '请输入商品英文名称' },
              {
                validator: goodsEnNameValidator,
                message: '不支持汉字，不能超过32个字符',
              },
            ]"
          />
          <Field
            v-model="item.goodsCnName"
            name="goodsCnName"
            label="商品中文名称"
            placeholder="请输入商品中文名称"
            :rules="[
              { required: true, message: '请输入商品中文名称' },
              { validator: goodsCnNameValidator, message: '不能超过32个字符' },
            ]"
          />
          <Field
            v-model="item.goodsQty"
            name="goodsQty"
            label="商品数量"
            placeholder="请输入商品数量"
            :rules="[
              { required: true, message: '请输入商品数量' },
              {
                validator: goodsQuantityValidator,
                message: '只支持数字或小数，不能超过2147483647',
              },
            ]"
          />
          <Field
            v-model="item.goodsUnit"
            name="goodsUnit"
            label="商品单位"
            placeholder="请选择"
            readonly
            is-link
            :rules="[{ required: true, message: '请选择商品单位' }]"
            @click="handleToShowUnitPicker(index)"
          />
          <Field
            v-model="item.goodsUnitPrice"
            name="goodsUnitPrice"
            label="商品单价"
            placeholder="请输入商品单价"
            :rules="[
              { required: true, message: '请输入商品单价' },
              {
                validator: amountValidator,
                message: '只支持数字（含小数点），不可超过15个字符',
              },
            ]"
          />
        </CellGroup>
      </div>
    </Form>
    <Popup v-model:show="showCategoryPicker" position="bottom">
      <Search
        v-model="categorySearchKey"
        @search="handleCategorySearch"
        placeholder="请输入搜索关键词"
      />
      <Picker
        :columns-field-names="{ text: 'label', value: 'value' }"
        :columns="categoryList"
        @confirm="onCategoryConfirm"
        @cancel="showCategoryPicker = false"
      />
    </Popup>
    <Popup v-model:show="showUnitPicker" position="bottom">
      <Picker
        :columns="unitList"
        @confirm="onUnitConfirm"
        @cancel="showUnitPicker = false"
      />
    </Popup>
    <div class="add__btn" @click="handleAddProduct">
      <Icon name="plus" /><span>添加商品</span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.contract__product {
  padding: 12px;
  .product__item {
    width: 100%;
    background: #ffffff;
    border-radius: 8px;
    padding: 0 12px;
    margin-bottom: 10px;
    .product__item-header {
      height: 40px;
      line-height: 40px;
      font-size: 16px;
      font-weight: 500;
      color: #222222;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .delete__btn {
        font-size: 14px;
        color: #3f84f3;
        line-height: 18px;
      }
    }
  }
  .add__btn {
    width: 100px;
    height: 28px;
    background: #eaf2ff;
    border-radius: 14px;
    font-size: 14px;
    font-weight: 500;
    color: #3f84f3;
    line-height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
  }
}
</style>
